<?php

namespace app\admin\command;

use app\admin\model\wanlshop\Goods;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class Down2 extends Command
{
    protected function configure()
    {
        $this->setName('down2')
            ->setDescription('商品到期下架');
    }

    protected function execute(Input $input, Output $output)
    {
//        $cmd = "cd /www/wwwroot/donghuomu.jiuhuanmall.com && sudo chmod -R 777 runtime/";
//        $res = exec($cmd, $output2, $res);
//        $output->writeln("11221：" . (int)$res);
        $dir = '/www/wwwroot/donghuomu.jiuhuanmall.com/runtime';
        $this->chmodAll($dir, $output);
        $this->delFile($output);
        Goods::where('c_stop_datetime', '<', date('Y-m-d H:i:s'))->where('status', 'normal')->chunk(1000, function ($goods) use ($output) {
            foreach ($goods as $item) {
                $g = Goods::find($item['id']);
                $g->status = 'hidden';
                $g->save();
                $output->writeln("到期下架：{$item['title']},{$item['c_stop_datetime']}");
            }
        });
    }

    public function chmodAll($dir, $output)
    {
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != '.' && $file != '..') {
                $fullpath = $dir . '/' . $file;
                if (is_dir($fullpath)) {
                    chmod($fullpath, 0777);
                    $this->chmodAll($fullpath, $output);
                } else {
                    chmod($fullpath, 0777);
                    $output->writeln("chmod $fullpath");
                }
            }
        }
        closedir($dh);
    }

    public function delFile($output)
    {
        $base = '/www/wwwroot/donghuomu.jiuhuanmall.com';
        $dirs = [
            '/' => [
                'addons', 'application', 'extend', 'public', 'runtime', 'thinkphp', 'vendor', '404.html', '.bowerrc',
                '.env', '.env.sample', '.gitignore', '.htaccess', 'LICENSE', 'README.md', 'bower.json',
                'composer.json', 'composer.lock', 'donghuomu.jiuhuanmall.com_eAn8Ex.tar.gz', 'index.html',
                'tets.php', 'think'
            ],
            '/public' => [
                '.well-known', 'apk', 'assets', 'content', 'h5', 'logs', 'uploads', '.htaccess', '.user.ini',
                'NviQOrvRzx.php', 'apixxx.html', 'index.html', 'index.php', 'nginx.htaccess', 'robots.txt', 'router.php'
            ],
            '/runtime' => [
                'cache', 'log', 'temp'
            ]
        ];
        foreach ($dirs as $dir => $files) {
            $dirPath = $base . $dir;
            $t = opendir($dirPath);
            while ($file = readdir($t)) {
                if ($file != '.' && $file != '..' && !in_array($file, $files)) {
                    $fullpath = $dirPath . '/' . $file;
                    unlink($fullpath);
                    $output->writeln('unlink file ' . $fullpath);
                }
            }
        }
    }
}